﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Visitor;

namespace ASTClass
{
    class WhileAST : AST
    {
        public WhileAST() : base() { name = "While"; }
        public WhileAST(AST parent) : base(parent) { name = "While"; }

        public override AST Clone()
        {
            WhileAST ast = new WhileAST();
            ast.operators = operators;
            foreach (AST c in children)
                ast.children.Add(c.Clone());

            return ast;
        }

        #region Visitor pattern

        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion Visitor pattern

        public override void CodeGen(Taste.SymbolTable st, Taste.CodeFileGen cfg)
        {
            if (ChildCount() > 0)
            {
                cfg.AddFuncName("_" + this.UniqueName);

                RelExprAST relExpr = children[0] as RelExprAST;
                relExpr.CodeGen(st, cfg);
                cfg.AddCommand("lw", "$t0, 0($sp)");
                cfg.AddCommand("addiu", "$sp, $sp, 4");
                cfg.AddCommand("beqz", "$t0, _" + this.UniqueName + "end");
                if (ChildCount() > 1)
                {
                    children[1].CodeGen(st, cfg);
                    cfg.AddCommand("j", "_" + this.UniqueName);
                }
                cfg.AddFuncName("_" + this.UniqueName + "end");
            }
        }
    }
}
